package com.bnyy.medicalHousekeeper.moudle.message.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.bnyy.common.Constant;
import com.bnyy.common.view.FormInfoItem;
import com.bnyy.gbp.permission.PermissionHelper;
import com.bnyy.medicalHousekeeper.DialogHelper;
import com.bnyy.medicalHousekeeper.PopupWindowHelper;
import com.bnyy.medicalHousekeeper.R;
import com.bnyy.medicalHousekeeper.UserInfoManager;
import com.bnyy.medicalHousekeeper.activity.MainActivity;
import com.bnyy.medicalHousekeeper.base.BaseActivityImpl;
import com.bnyy.medicalHousekeeper.bean.ShareData;
import com.bnyy.medicalHousekeeper.moudle.message.MessageManager;
import com.bnyy.medicalHousekeeper.moudle.message.adapter.GroupChatMemberAdapter;
import com.bnyy.medicalHousekeeper.request.BaseObserverImpl;
import com.bnyy.medicalHousekeeper.request.RequestManager;
import com.bnyy.message.bean.Contact;
import com.bnyy.message.bean.ContactGroup;
import com.bnyy.message.bean.ContactUser;
import com.bnyy.message.bean.GroupChatSetting;
import com.bnyy.message.bean.chat.Chat;
import com.bnyy.message.bean.chat.message_data.InvitationMessage;
import com.bnyy.message.enums.GroupChatIdentity;
import com.bnyy.message.event.ReceiveMessageEvent;
import com.kyleduo.switchbutton.SwitchButton;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.function.Consumer;
import java.util.function.Predicate;

import butterknife.BindView;
import cn.bingoogolapple.qrcode.zxing.QRCodeEncoder;

/**
 * Author : 关炳鹏
 * Description :
 * Date : 2022/11/10
 **/
public class GroupChatSettingActivity extends BaseActivityImpl {
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.form_group_name)
    FormInfoItem formGroupName;
    @BindView(R.id.form_group_type)
    FormInfoItem formGroupType;
    @BindView(R.id.tv_group_notice)
    TextView tvGroupNotice;
    @BindView(R.id.tv_group_notice_content)
    TextView tvGroupNoticeContent;
    @BindView(R.id.switch_button_dont_disturb)
    SwitchButton switchButtonDontDisturb;
    @BindView(R.id.switch_button_topping)
    SwitchButton switchButtonTopping;
    @BindView(R.id.form_report)
    FormInfoItem formReport;
    @BindView(R.id.tv_clear_record)
    TextView tvClearRecord;
    @BindView(R.id.tv_group_chat_manage)
    TextView tvGroupChatManage;
    @BindView(R.id.tv_delete)
    TextView tvDelete;
    @BindView(R.id.tv_dismiss)
    TextView tvDismiss;
    @BindView(R.id.ll_group_type)
    LinearLayout llGroupType;

    private GroupChatMemberAdapter adapter;
    private GroupChatSetting groupChatSetting;
    private int groupChatId;
    private Chat chat;

    private ActivityResultLauncher<Intent> addGroupChatMemberLauncher, // 新增群员回调
            removeGroupChatMemberLauncher, // 移除群员回调
            editGroupChatNameLauncher, // 编辑群名回调
            editGroupChatNoticeLauncher, // 编辑群公告回调
            groupChatManagerLauncher, // 群管理回调
            relevantInfoLauncher; // 动态信息管理回调

    public static void show(Context context, Chat chat) {
        Intent intent = new Intent(context, GroupChatSettingActivity.class);
        intent.putExtra("chat", chat);
        context.startActivity(intent);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_message_group_chat_setting;
    }

    @Override
    public String getTitleStr() {
        return "群聊设置";
    }

    @Override
    public boolean registerEventBus() {
        return true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(Integer tag) {
        if (tag == Constant.EventBusTag.REFRESH_OBSERVER) {
            HashMap<String, Object> params = new HashMap<>();
            params.put("id", groupChatId);
            requestManager.request(requestManager.mMessageRetrofitService.getGroupChatSetting(RequestManager.getJsonRequestBody(params)),
                    new BaseObserverImpl<GroupChatSetting>(mContext) {
                        @Override
                        public void onSuccess(GroupChatSetting groupChatSetting) {
                            super.onSuccess(groupChatSetting);
                            GroupChatSettingActivity.this.groupChatSetting = groupChatSetting;

                            refreshMembers();
                        }
                    });
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(ReceiveMessageEvent event) {
        switch (event.getMessageType()) {
            case GROUP_CHAT_MANAGER_ADD:
            case GROUP_CHAT_MANAGER_REMOVE:
                HashMap<String, Object> params = new HashMap<>();
                params.put("id", groupChatId);
                requestManager.request(requestManager.mMessageRetrofitService.getGroupChatSetting(RequestManager.getJsonRequestBody(params)),
                        new BaseObserverImpl<GroupChatSetting>(mContext) {
                            @Override
                            public void onSuccess(GroupChatSetting groupChatSetting) {
                                super.onSuccess(groupChatSetting);

                                GroupChatSettingActivity.this.groupChatSetting = groupChatSetting;

                                init();
                            }
                        });
                break;
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        chat = (Chat) getIntent().getSerializableExtra("chat");
        groupChatId = chat.getRecipientId();

        addGroupChatMemberLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
                new ActivityResultCallback<ActivityResult>() {
                    @Override
                    public void onActivityResult(ActivityResult result) {
                        Intent data = result.getData();
                        if (data != null) {
                            ArrayList<Contact> contacts = (ArrayList<Contact>) data.getSerializableExtra(SelectContactActivity.RESULT_SELECTED_CONTACTS);
                            if (contacts != null && contacts.size() > 0) {
                                HashMap<String, Object> params = new HashMap<>();
                                params.put("id", groupChatId);
                                ArrayList<HashMap<String, Integer>> users = new ArrayList<>();
                                contacts.forEach(new Consumer<Contact>() {
                                    @Override
                                    public void accept(Contact contact) {
                                        HashMap<String, Integer> map = new HashMap<>();
                                        map.put("id", contact.getId());
                                        map.put("role_id", contact.getRole_id());
                                        users.add(map);
                                    }
                                });
                                params.put("user_id", userInfoManager.getLoginUserId());
                                params.put("users", users);

                                requestManager.request(requestManager.mMessageRetrofitService.addGroupChatMember(RequestManager.getJsonRequestBody(params)),
                                        new BaseObserverImpl<Object>(mContext) {
                                            @Override
                                            public void onSuccess() {
                                                super.onSuccess();
                                                HashMap<String, Object> params = new HashMap<>();
                                                params.put("id", groupChatId);
                                                requestManager.request(requestManager.mMessageRetrofitService.getGroupChatSetting(RequestManager.getJsonRequestBody(params)),
                                                        new BaseObserverImpl<GroupChatSetting>(mContext) {
                                                            @Override
                                                            public void onSuccess(GroupChatSetting groupChatSetting) {
                                                                super.onSuccess(groupChatSetting);
                                                                GroupChatSettingActivity.this.groupChatSetting = groupChatSetting;

                                                                refreshMembers();
                                                            }
                                                        });
                                            }
                                        });
                            }
                        }
                    }
                });

        removeGroupChatMemberLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
                new ActivityResultCallback<ActivityResult>() {
                    @Override
                    public void onActivityResult(ActivityResult result) {
                        Intent data = result.getData();
                        if (data != null) {
                            ArrayList<Contact> contacts = (ArrayList<Contact>) data.getSerializableExtra(SelectContactActivity.RESULT_SELECTED_CONTACTS);
                            if (contacts != null && contacts.size() > 0) {
                                HashMap<String, Object> params = new HashMap<>();
                                params.put("id", groupChatId);
                                ArrayList<HashMap<String, Integer>> users = new ArrayList<>();
                                contacts.forEach(new Consumer<Contact>() {
                                    @Override
                                    public void accept(Contact contact) {
                                        HashMap<String, Integer> map = new HashMap<>();
                                        map.put("id", contact.getId());
                                        map.put("role_id", contact.getRole_id());
                                        users.add(map);
                                    }
                                });
                                params.put("users", users);

                                HashSet<Integer> selectedContactIds = (HashSet<Integer>) data.getSerializableExtra(SelectContactActivity.RESULT_SELECTED_CONTACT_IDS);

                                requestManager.request(requestManager.mMessageRetrofitService.removeGroupChatMember(RequestManager.getJsonRequestBody(params)),
                                        new BaseObserverImpl<Object>(mContext) {
                                            @Override
                                            public void onSuccess() {
                                                super.onSuccess();

                                                groupChatSetting.getUser_list().removeIf(new Predicate<ContactGroup.Member>() {
                                                    @Override
                                                    public boolean test(ContactGroup.Member member) {
                                                        return selectedContactIds.contains(member.getId());
                                                    }
                                                });

                                                refreshMembers();
                                            }
                                        });
                            }
                        }
                    }
                });

        editGroupChatNameLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
                new ActivityResultCallback<ActivityResult>() {
                    @Override
                    public void onActivityResult(ActivityResult result) {
                        Intent data = result.getData();
                        if (data != null) {
                            String groupChatName = data.getStringExtra("groupChatName");
                            formGroupName.setContent(groupChatName);
                            groupChatSetting.setGroup_name(groupChatName);
                        }
                    }
                });

        editGroupChatNoticeLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
                new ActivityResultCallback<ActivityResult>() {
                    @Override
                    public void onActivityResult(ActivityResult result) {
                        Intent data = result.getData();
                        if (data != null) {
                            String groupChatNotice = data.getStringExtra("groupChatNotice");
                            groupChatSetting.setGroup_board(groupChatNotice);
                            tvGroupNoticeContent.setText(groupChatNotice);
                        }
                    }
                });

        groupChatManagerLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
                new ActivityResultCallback<ActivityResult>() {
                    @Override
                    public void onActivityResult(ActivityResult result) {
                        Intent data = result.getData();
                        if (data != null) {
                            groupChatSetting = (GroupChatSetting) data.getSerializableExtra("groupChatSetting");
                        }
                    }
                });

        relevantInfoLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
                new ActivityResultCallback<ActivityResult>() {
                    @Override
                    public void onActivityResult(ActivityResult result) {
                        Intent data = result.getData();
                        if (data != null) {
                            ArrayList<GroupChatSetting.RelevantInfo> relevantInfos = (ArrayList<GroupChatSetting.RelevantInfo>) data.getSerializableExtra("relevantInfos");
                            groupChatSetting.setRelevantInfo(relevantInfos);
                        }
                    }
                });

        recyclerView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                recyclerView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                int spanCount = 5;
                recyclerView.setLayoutManager(new GridLayoutManager(mContext, spanCount));
                int itemWidth = (recyclerView.getWidth() - ((spanCount + 1) * recyclerView.getPaddingStart())) / spanCount;
                adapter = new GroupChatMemberAdapter(mContext, itemWidth,
                        new GroupChatMemberAdapter.Operate() {

                            @Override
                            public void onAdd() {
                                switch (groupChatSetting.getGroup_type()) {
                                    case 1:
//                                        AddFamilyMemberActivity.show(mContext, groupChatSetting.getWear_id());
                                        break;
                                    case 2:
                                        requestManager.request(requestManager.mMessageRetrofitService.getFriendList(),
                                                new BaseObserverImpl<ArrayList<ContactUser>>(mContext) {
                                                    @Override
                                                    public void onSuccess(ArrayList<ContactUser> contactUsers) {
                                                        super.onSuccess(contactUsers);
                                                        HashSet<Integer> memberIds = new HashSet<>();

                                                        ArrayList<ContactUser> target = new ArrayList<>();
                                                        if (contactUsers != null && contactUsers.size() > 0) {
                                                            for (ContactGroup.Member member : groupChatSetting.getUser_list()) {
                                                                memberIds.add(member.getId());
                                                            }

                                                            for (ContactUser contactUser : contactUsers) {
                                                                if (!memberIds.contains(contactUser.getId())) {
                                                                    target.add(contactUser);
                                                                }
                                                            }
                                                        }
                                                        SelectContactActivity.show(
                                                                mContext,
                                                                "添加群成员",
                                                                "确认要添加选中的好友吗",
                                                                false,
                                                                true,
                                                                null,
                                                                target,
                                                                addGroupChatMemberLauncher
                                                        );

//                                                        if (target.size() > 0) {
//                                                            SelectContactActivity.show(
//                                                                    mContext,
//                                                                    "添加群成员",
//                                                                    "确认要添加选中的好友吗",
//                                                                    false,
//                                                                    true,
//                                                                    null,
//                                                                    target,
//                                                                    addGroupChatMemberLauncher
//                                                            );
//                                                        } else {
//                                                            Toast.makeText(mContext, "暂无可邀请的好友", Toast.LENGTH_SHORT).show();
//                                                        }
                                                    }
                                                });
                                        break;
                                }
                            }

                            @Override
                            public void onRemove(ArrayList<ContactGroup.Member> members) {

                                GroupChatIdentity groupAuthority = GroupChatIdentity.getGroupAuthority(groupChatSetting.getAuth_type());

                                ArrayList<ContactGroup.Member> target = new ArrayList<>();
                                switch (groupAuthority) {
                                    case MANAGER: // 管理员可以移除群成员
                                        for (ContactGroup.Member member : members) {
                                            if (GroupChatIdentity.getGroupAuthority(member.getAuth_type()) == GroupChatIdentity.MEMBER) {
                                                target.add(member);
                                            }
                                        }
                                        break;
                                    case GROUP_LEADER: // 群主可以移除除自己外的所有人
                                        for (ContactGroup.Member member : members) {
                                            if (member.getId() != UserInfoManager.getInstance().getLoginUserId()) {
                                                if (GroupChatIdentity.getGroupAuthority(member.getAuth_type()) != GroupChatIdentity.GROUP_LEADER) {
                                                    target.add(member);
                                                }
                                            }
                                        }
                                        break;
                                }
                                SelectContactActivity.show(
                                        mContext,
                                        "移除群成员",
                                        "确认要移除选中的群成员吗",
                                        false,
                                        true,
                                        null,
                                        target, removeGroupChatMemberLauncher
                                );
                            }

                            @Override
                            public void onClick(ContactGroup.Member member) {
                                UserHomePageActivity.show(mContext, member.getId(), member.getRole_id());
                            }
                        });
                HashMap<String, Object> params = new HashMap<>();
                params.put("id", groupChatId);
                requestManager.request(requestManager.mMessageRetrofitService.getGroupChatSetting(RequestManager.getJsonRequestBody(params)),
                        new BaseObserverImpl<GroupChatSetting>(mContext) {
                            @Override
                            public void onSuccess(GroupChatSetting groupChatSetting) {
                                super.onSuccess(groupChatSetting);

                                GroupChatSettingActivity.this.groupChatSetting = groupChatSetting;

                                init();
                            }
                        });
            }
        });
    }

    private void init() {
        formGroupName.setContent(groupChatSetting.getGroup_name());

        GroupChatIdentity groupAuthority = GroupChatIdentity.getGroupAuthority(groupChatSetting.getAuth_type());

        if (groupAuthority == GroupChatIdentity.MEMBER) {
            if (groupChatSetting.getGroup_admin().isAuth_rename()) {
                formGroupName.setType(FormInfoItem.READ_ONLY);
            } else {
                formGroupName.setType(FormInfoItem.PRESS);
            }
        }

        tvDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogHelper.showNormalDialog(mContext, "确定要退出群聊【" + groupChatSetting.getGroup_name() + "】吗？", new DialogHelper.Callback() {
                    @Override
                    public void onRightClick(AlertDialog alertDialog) {
                        super.onRightClick(alertDialog);
                        HashMap<String, Object> params = new HashMap<>();
                        params.put("id", groupChatId);
                        requestManager.request(requestManager.mMessageRetrofitService.exiteGroupChat(RequestManager.getJsonRequestBody(params)),
                                new BaseObserverImpl<Object>(mContext) {
                                    @Override
                                    public void onSuccess() {
                                        super.onSuccess();
                                        MessageManager.deleteChat(chat.getChatId());
                                        MainActivity.show(mContext);
                                    }
                                });
                    }
                });
            }
        });

        formGroupName.setOnPressListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EditGroupChatNameActivity.show(mContext, groupChatId, groupChatSetting.getGroup_name(), editGroupChatNameLauncher);
            }
        });

        switch (groupChatSetting.getGroup_type()) {
            case 1:
                if (groupAuthority == GroupChatIdentity.MEMBER) {
                    llGroupType.setVisibility(View.GONE);
                    tvDelete.setVisibility(View.VISIBLE);
                }
                formGroupType.setTitle("动态信息关联");
                formGroupType.setOnPressListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        RelevantInfoActivity.show(mContext, groupChatSetting, relevantInfoLauncher);
                    }
                });
                break;
            case 2:
                switch (groupAuthority) {
                    case MEMBER:
                    case MANAGER:
                        tvDelete.setVisibility(View.VISIBLE);
                        break;
                    case GROUP_LEADER:
                        tvGroupChatManage.setVisibility(View.VISIBLE);
                        tvGroupChatManage.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                GroupChatManageActivity.show(mContext, groupChatSetting, groupChatManagerLauncher);
                            }
                        });

                        tvDismiss.setVisibility(View.VISIBLE);
                        tvDismiss.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                DialogHelper.showNormalDialog(mContext, "确定要解散群聊吗？",
                                        new DialogHelper.Callback() {
                                            @Override
                                            public void onRightClick(AlertDialog alertDialog) {
                                                super.onRightClick(alertDialog);

                                                HashMap<String, Integer> params = new HashMap<>();
                                                params.put("id", groupChatSetting.getId());
                                                requestManager.request(requestManager.mMessageRetrofitService.dismissGroupChat(RequestManager.getJsonRequestBody(params)),
                                                        new BaseObserverImpl<Object>() {
                                                            @Override
                                                            public void onSuccess() {
                                                                super.onSuccess();
                                                                Toast.makeText(mContext, "群聊已解散", Toast.LENGTH_SHORT).show();
                                                                finish();
                                                            }
                                                        });
                                            }
                                        });
                            }
                        });
                        break;
                }

                formGroupType.setTitle("分享群邀请");
                formGroupType.setOnPressListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        HashMap<String, Object> params = new HashMap<>();
                        params.put("type", 1);
                        params.put("group_id", groupChatSetting.getId());
                        requestManager.request(requestManager.mJavaRetrofitService.share(RequestManager.getJsonRequestBody(params)),
                                new BaseObserverImpl<ShareData>(mContext) {
                                    @Override
                                    public void onSuccess(ShareData shareData) {
                                        super.onSuccess(shareData);

                                        View view = inflater.inflate(R.layout.pop_win_message_share, null);

                                        PopupWindow popupWindow = PopupWindowHelper.getInstance(mContext).show(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);

                                        TextView tvName = view.findViewById(R.id.tv_name);
                                        tvName.setText(groupChatSetting.getGroup_name());

                                        TextView tvOvertime = view.findViewById(R.id.tv_overtime);
                                        tvOvertime.setText("该二维码将于" + shareData.getEdt().split(" ")[0] + "到期");

                                        ImageView ivQrcode = view.findViewById(R.id.iv_qrcode);

                                        new Thread(new Runnable() {
                                            @Override
                                            public void run() {
                                                Bitmap bitmap = QRCodeEncoder.syncEncodeQRCode(shareData.getUrl(), ScreenUtils.getScreenWidth() / 5 * 2);
                                                ivQrcode.post(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        ivQrcode.setImageBitmap(bitmap);
                                                    }
                                                });
                                            }
                                        }).start();

                                        view.findViewById(R.id.tv_chat).setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                InvitationMessage invitationMessage = new InvitationMessage();
                                                invitationMessage.setContent(userInfoManager.getLoginUserInfo().getUsername() + "邀请你加入" + groupChatSetting.getGroup_name() + "群");
                                                invitationMessage.setId(groupChatSetting.getId());
                                                for (ContactGroup.Member member : groupChatSetting.getUser_list()) {
                                                    if (member.getGroupChatIdentity() == GroupChatIdentity.GROUP_LEADER) {
                                                        invitationMessage.setImg(member.getUser_img());
                                                        break;
                                                    }
                                                }
                                                Share2ContactsActivity.show(mContext, invitationMessage);
                                                popupWindow.dismiss();
                                            }
                                        });
                                        view.findViewById(R.id.tv_wechat).setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                Bitmap bitmap = ImageUtils.view2Bitmap(view.findViewById(R.id.ll_share_content));

                                                //初始化 WXImageObject 和 WXMediaMessage 对象
//                                                WXImageObject imgObj = new WXImageObject(bitmap);
//                                                WXMediaMessage msg = new WXMediaMessage();
//                                                msg.mediaObject = imgObj;
//
//                                                //设置缩略图
//                                                Bitmap thumbBmp = Bitmap.createScaledBitmap(bitmap, 160, 320, true);
//                                                bitmap.recycle();
//
//                                                ByteArrayOutputStream baos = new ByteArrayOutputStream();
//                                                thumbBmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
//                                                thumbBmp.recycle();
//                                                msg.thumbData = baos.toByteArray();
//                                                //构造一个Req
//                                                SendMessageToWX.Req req = new SendMessageToWX.Req();
//                                                req.transaction = "img_" + System.currentTimeMillis();
//                                                req.message = msg;
//                                                req.scene = SendMessageToWX.Req.WXSceneSession;
//                                                // req.userOpenId = Constant.WX.APP_ID;
//                                                //调用api接口，发送数据到微信
//                                                IWXAPI api = WXAPIFactory.createWXAPI(mContext, Constant.WX.APP_ID);
//                                                api.sendReq(req);
                                                popupWindow.dismiss();

                                            }
                                        });
                                        view.findViewById(R.id.tv_save).setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                PermissionHelper.getInstance().requestPermission(new PermissionHelper.RequestPermission() {
                                                    @Override
                                                    public String[] permissions() {
                                                        return new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
                                                    }

                                                    @Override
                                                    public void granted(HashSet<String> granted) {
                                                        Bitmap bitmap = ImageUtils.view2Bitmap(view.findViewById(R.id.ll_share_content));

                                                        ImageUtils.save2Album(bitmap, Bitmap.CompressFormat.JPEG);

                                                        Toast.makeText(mContext, "已成功保存到相册", Toast.LENGTH_SHORT).show();

                                                        popupWindow.dismiss();
                                                    }

                                                    @Override
                                                    public void denied(HashSet<String> denied) {

                                                    }
                                                });
                                            }
                                        });
                                    }
                                });
                    }
                });
                break;
        }

        String groupChatNotice = groupChatSetting.getGroup_board();
        if (!TextUtils.isEmpty(groupChatNotice)) {
            tvGroupNoticeContent.setText(groupChatNotice);
        }
        tvGroupNoticeContent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tvGroupNotice.performClick();
            }
        });
        tvGroupNotice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (groupAuthority == GroupChatIdentity.MEMBER) {
                    if (TextUtils.isEmpty(groupChatNotice)) {
                        Toast.makeText(mContext, "暂无群公告", Toast.LENGTH_SHORT).show();
                    } else {
                        GroupChatNoticeActivity.show(mContext, groupChatSetting);
                    }
                } else {
                    GroupChatNoticeActivity.show(mContext, groupChatSetting, editGroupChatNoticeLauncher);
                }
            }
        });

        tvClearRecord.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogHelper.showNormalDialog(mContext, "确定要清除聊天记录吗？", new DialogHelper.Callback() {
                    @Override
                    public void onRightClick(AlertDialog alertDialog) {
                        super.onRightClick(alertDialog);
                        MessageManager.deleteChatMessage(chat.getChatId());
                    }
                });
            }
        });

        switchButtonDontDisturb.setChecked(groupChatSetting.isNoDisturb());
        switchButtonDontDisturb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                HashMap<String, Object> params = new HashMap<>();
                params.put("id", groupChatSetting.getId());
                params.put("no_disturb", switchButtonDontDisturb.isChecked());
                requestManager.request(requestManager.mMessageRetrofitService.editGroupChatSetting(RequestManager.getJsonRequestBody(params)),
                        new BaseObserverImpl<Object>(mContext) {

                            @Override
                            public void onSuccess() {
                                super.onSuccess();
                                groupChatSetting.setNoDisturb(switchButtonDontDisturb.isChecked());
                            }

                            @Override
                            public void onOtherCode(int code) {
                                super.onOtherCode(code);
                                switchButtonDontDisturb.setChecked(!switchButtonDontDisturb.isChecked());
                            }

                            @Override
                            public void onError(Throwable e) {
                                super.onError(e);
                                switchButtonDontDisturb.setChecked(!switchButtonDontDisturb.isChecked());
                            }
                        });
            }
        });
        switchButtonTopping.setChecked(groupChatSetting.isTopping());
        switchButtonTopping.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                HashMap<String, Object> params = new HashMap<>();
                params.put("id", groupChatSetting.getId());
                params.put("is_stick", switchButtonTopping.isChecked());
                requestManager.request(requestManager.mMessageRetrofitService.editGroupChatSetting(RequestManager.getJsonRequestBody(params)),
                        new BaseObserverImpl<Object>(mContext) {

                            @Override
                            public void onSuccess() {
                                super.onSuccess();
                                groupChatSetting.setTopping(switchButtonTopping.isChecked());

                                MessageManager.setGroupChatTopping(groupChatId, switchButtonTopping.isChecked());

                                MessageManager.setGroupChatTopping(groupChatId, switchButtonTopping.isChecked());
                            }

                            @Override
                            public void onOtherCode(int code) {
                                super.onOtherCode(code);
                                switchButtonTopping.setChecked(!switchButtonTopping.isChecked());
                            }

                            @Override
                            public void onError(Throwable e) {
                                super.onError(e);
                                switchButtonTopping.setChecked(!switchButtonTopping.isChecked());
                            }
                        });
            }
        });

        recyclerView.setAdapter(adapter);

        refreshMembers();
    }

    private void refreshMembers() {
        if (adapter == null) {
            return;
        }
        GroupChatIdentity groupAuthority = GroupChatIdentity.getGroupAuthority(groupChatSetting.getAuth_type());
        ArrayList<ContactGroup.Member> members = groupChatSetting.getUser_list();
        boolean enableAdd = false, enableRemove = false;
        switch (groupAuthority) {
            case MEMBER:
                enableAdd = false;
                enableRemove = false;
                break;
            case MANAGER:
                enableAdd = true;
                for (ContactGroup.Member member : members) {
                    if (GroupChatIdentity.getGroupAuthority(member.getAuth_type()) == GroupChatIdentity.MEMBER) {
                        enableRemove = true;
                        break;
                    }
                }
                break;
            case GROUP_LEADER:
                enableAdd = true;
                enableRemove = true;
                break;
        }
        if (members.size() <= 1) {
            enableRemove = false;
        }
        adapter.refresh(enableAdd, enableRemove, members);
    }

}



























